<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>图层绑定</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/libs/layui2.2.5/css/layui.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/common.css">
    <link rel="icon" href="${pageContext.request.contextPath}/static/libs/uiframe/frame/static/image/code.png">
    <!--
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/libs/ol4.5.0/ol.css">
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/libs/ol4.5.0/ol.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/libs/iclient9-openlayers/iclient-openlayers.min-9.0.0-742.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/spatial/js/c3gis.js"></script>
    -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/spatial/js/hbgis.js"></script>
    <style type="text/css">
        .layui-form-item {
            margin-bottom: 10px;
            clear: both;
        }
        .layui-table {
            width: 100%;
            margin: 0px;
            background-color: #fff;
        }
        .layui-table-cell .layui-form-checkbox {
            top: 6px;
        }
        .layui-input-block {
            margin-left: 100px;
            min-height: 36px;
        }
        .layui-table-view {
            position: relative;
            margin: 0px 0;
            overflow: hidden;
        }
        .layui-form-label {
            float: left;
            display: block;
            padding: 9px 10px;
            width: 80px;
            font-weight: 400;
            text-align: right;
        }
    </style>
</head>
<body>
<div class="layui-col-md3">
    <table id="layerlist" class="layui-table" lay-filter="layerlist"></table>
    <script type="text/html" id="layerbar">
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="order_up"><i class="layui-icon">&#xe619;</i></a>
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="order_down"><i class="layui-icon">&#xe61a;</i></a>
    </script>
    <div class="layui-form-item" style="margin-top: 15px">
        <div class="layui-input-block" style="margin-left:80px">
            <button class="layui-btn" lay-submit="" id="sourcebind">提 交</button>
            <%--<button id="refresh" class="layui-btn">刷新</button>--%>
            <button type="reset" class="layui-btn">重 置</button>
        </div>
    </div>
</div>
<div class="layui-col-md9">
    <div id="map" style="margin:0 auto;width: 100%;height:100%;"></div>
</div>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/libs/layui2.2.5/layui.js"></script>
<script>
    var $,table,form,layer,mapId = '${mapId}',gis;

    /**
     * 初始化右侧table
     */
    layui.use(['table','form', 'layer'], function () {
        var tableIns,layerData;

        $ = layui.jquery;
        table = layui.table;
        form = layui.form;
        layer = layui.layer;

        /**
         * 图层列表初始化
         * */
        $.ajax({
            type:'get',
            url:'${pageContext.request.contextPath}/ol/map/layerlist?mapid=' + mapId,
            dataType: "json",
            contentType:'application/json;charset=utf-8',
            success:function(data) {
                if(data != null && data.hasOwnProperty("layer") && data["layer"].length > 0){
                    var hasBinded = [],noBinded=[];

                    if(data["mapLayers"] != null && data["mapLayers"].length > 0){
                        for(var index = 0,lenIndex = data["mapLayers"].length;index < lenIndex;index++){
                            for(var indexLayer=0,lenIndexLayer = data["layer"].length;indexLayer < lenIndexLayer;indexLayer++){
                                if(data["mapLayers"][index] == data["layer"][indexLayer]["layerId"]){
                                    data["layer"][indexLayer]["LAY_CHECKED"] = true;
                                    hasBinded.push(data["layer"][indexLayer]);
                                    break;
                                }
                            }
                        }
                    }
                    for(var i = 0,len = data["layer"].length;i < len;i++){
                        if($.inArray(data["layer"][i]["layerId"],data["mapLayers"]) < 0){
                            data["layer"][i]["LAY_CHECKED"] = false;
                            noBinded.push(data["layer"][i]);
                        }

                    }
                    layerData = hasBinded.concat(noBinded);
                    tableIns = table.render({
                        id: 'layerlist'
                        ,elem: '#layerlist'
                        ,height: 'full-75'
                        ,data:layerData
                        ,cols: [[
                            {checkbox: true, LAY_CHECKED: false}
                            ,{field: 'layerName', align:'center', title: '图层名称', width: 170}
                            ,{fixed: 'right', align:'center',title: '操作', width: 100, toolbar: '#layerbar'}
                        ]]
                    });
                }else {
                    layerData = [];
                }
            },
            error: function (error){
                console.log(error);
            }
        });

        /**
         * 图层选择事件
         * */
        table.on('checkbox(layerlist)', function(obj){
            var checkStatus = table.checkStatus('layerlist'),layerIds=[];
            for(var i = 0,len = layerData.length;i < len;i++){
                if(obj.type == "one"){
                    if(obj.data.layerId == layerData[i].layerId){
                        layerIds.push(layerData[i].layerId);
                        layerData[i].LAY_CHECKED = obj["checked"];
                        break;
                    }
                }else if(obj.type == "all"){
                    layerData[i].LAY_CHECKED = obj["checked"];
                    layerIds.push(layerData[i].layerId);
                }
            }
            switchLayersById(layerIds,obj["checked"]);
        });

        /**
         * 图层顺序变更事件
         * */
        table.on('tool(layerlist)', function(obj){
            var data = obj.data
                ,layEvent = obj.event,tmp;
            for(var i = 0,len = layerData.length;i < len;i++){
                if(layerData[i]["layerId"] == data["layerId"]){
                    if(layEvent === 'order_up'){
                        if(i == 0){
                            return;
                        }
                        tmp = layerData[i-1];
                        layerData[i-1] = layerData[i];
                        layerData[i] = tmp;

                    }else if(layEvent === 'order_down'){
                        if(i == len-1){
                            return;
                        }
                        tmp = layerData[i+1];
                        layerData[i+1] = layerData[i];
                        layerData[i] = tmp;
                    }
                    table.reload("layerlist",{
                        data:layerData
                    });
                    changeLayerIndex();
                    break;
                }
            }

        });

        /**
         *  提交按钮绑定事件
         * */
        $("#sourcebind").click(function () {
            var checkStatus = table.checkStatus('layerlist')
                ,checkData = checkStatus.data,layerIds=[];
            if(checkData.length > 0){
                for(var i = 0,len = checkData.length;i < len;i++){
                    layerIds.push(checkData[i]["layerId"]);
                }
            }
            $.ajax({
                type:'post',
                url:'${pageContext.request.contextPath}/ol/map/layerbind',
                dataType: "json",
                contentType:'application/json;charset=utf-8',
                data:JSON.stringify({
                    mapId:mapId,
                    layerIds:layerIds
                }),
                success:function(data) {
                    layer.msg(data.status);
                    window.parent.layIndex = null;
                    window.parent.closeAllLayer();
                },
                error: function (error){
                    console.log(error);
                }
            });
        });


        /**
         * 初始化地图
         */
        //mapInit();
        gis = new C3GIS(mapId,'map');

    });

    <%--function mapInit() {--%>
        <%--var c3gis = null;--%>
        <%--$.ajax({--%>
            <%--type:'get',--%>
            <%--url:'${pageContext.request.contextPath}/ol/map/mapentry?mapid='+mapId,--%>
            <%--dataType: "json",--%>
            <%--success:function(data) {--%>
                <%--if(data != null){--%>
                    <%--gis = new C3GIS({--%>
                        <%--target:"map",--%>
                        <%--center: data["view"]["center"] == null ?[118.360772748187, 36.13540951960175]:data["view"]["center"],--%>
                        <%--zoom: data["view"]["zoom"] == null ? 9:data["view"]["zoom"],--%>
                        <%--projection: data["view"]["projection"] == null ? "EPSG:4326":data["view"]["projection"]--%>
                    <%--});--%>

                    <%--if(data["layers"] != null && data["layers"].length > 0){--%>
                        <%--addLayerByIds(data["layers"]);--%>
                    <%--}--%>
                <%--}--%>
            <%--},--%>
            <%--error: function (error){--%>
                <%--console.log(error);--%>
            <%--}--%>
        <%--});--%>
    <%--}--%>

    function switchLayersById(layerIds,isSelected) {
        if(isSelected){
            addLayerByIds(layerIds);
        }else{
            hideLayerByIds(layerIds);
        }
    }

    /**
     * 处理新增图层方法，如果图层已存在则显示该图层，如果图层不存在则读取图层信息后加入地图
     * @param layerIds
     */
    function addLayerByIds(layerIds) {
        if(layerIds != null && layerIds.length > 0){
            var newLayer = [],existedLayer = null;
            // 显示被隐藏的图层
            for(var i = layerIds.length - 1;i >= 0;i--){
                existedLayer = gis.getLayerById(layerIds[i]);
                if(existedLayer != null){
                    existedLayer.setVisible(true);
                }else {
                    newLayer.push(layerIds[i]);
                }
            }
            // 添加不存在的图层
            if(newLayer.length > 0){
                $.ajax({
                    type:'get',
                    url:'${pageContext.request.contextPath}/ol/layer/layerentries?layerids='+newLayer.join(","),
                    dataType: "json",
                    success:function(data) {
                        if(data.length > 0){
                            var olLayer;
                            for(var i = 0,len = data.length;i < len;i++){
                                if(data[i]['source']['type'] != 'ol.supermap.FeatureService' && data[i]['source']['type'] != 'arcgis.FeatureService'){
                                    olLayer = getLayerFromLayerSource(data[i]);
                                }else {
                                    olLayer = data[i]['layer'];
                                    olLayer['source'] = data[i]['source']
                                }
                                gis.addLayer(olLayer["type"],olLayer["layerName"],olLayer);
                                changeLayerIndex();
                            }
                        }
                    },
                    error: function (error){
                        console.log(error);
                    }
                });
            }else {
                changeLayerIndex();
            }
        }
    }

    function hideLayerByIds(layerIds) {
        if(layerIds != null && layerIds.length > 0){
            var selectedLayer;
            for(var i = 0,len = layerIds.length;i < len;i++){
                selectedLayer = gis.getLayerById(layerIds[i]).getProperties();
                if(selectedLayer["layerType"] == "ol.layer.Vector"){
                    gis.removeAllSelectInteraction();
                }
                gis.hideLayerById(layerIds[i]);
            }
            changeLayerIndex();
        }
    }

    function getLayerFromLayerSource(layerSource) {
        if(layerSource.source != null){
            layerSource.layer.source = gis.createSourceByType(layerSource.source.type,layerSource.source.options);
        }
        return layerSource.layer;
    }
    
    function changeLayerIndex() {
        var checkStatus = table.checkStatus('layerlist')
            , data = checkStatus.data
            , pointerMove
            , click
            , style
            , callBack
            , isForced = false;
        if(data.length > 0){
            for(var i = 0,len = data.length;i < len;i++){
                if(data[i]["type"] == "ol.layer.Vector"){
                    if(i == 0){
                        gis.removeAllSelectInteraction();
                        isForced = true;

                        if(data[0].hasOwnProperty("options")
                            && data[0]["options"] != null
                            && data[0]["options"].hasOwnProperty("stylePointerMove")
                            && data[0]["options"]["stylePointerMove"].hasOwnProperty("code")
                            && data[0]["options"]["stylePointerMove"]["code"] != ""){
                            style = eval('(' + data[0]["options"]["stylePointerMove"]["code"] + ')');
                        }else {
                            style = null;
                        }
                        if(data[0].hasOwnProperty("options")
                            && data[0]["options"] != null
                            && data[0]["options"].hasOwnProperty("pointerMove")
                            && data[0]["options"]["pointerMove"].hasOwnProperty("code")
                            && data[0]["options"]["pointerMove"]["code"] != ""){
                            callBack = eval('(' + data[0]["options"]["pointerMove"]["code"] + ')');
                        }else {
                            callBack = null;
                        }
                        if(style != null || callBack != null){
                            gis.addInteraction(data[i]["layerName"],"pointerMove",style,callBack);
                        }


                        if(data[0].hasOwnProperty("options")
                            && data[0]["options"] != null
                            && data[0]["options"].hasOwnProperty("styleClick")
                            && data[0]["options"]["styleClick"].hasOwnProperty("code")
                            && data[0]["options"]["styleClick"]["code"] != ""){
                            style = eval('(' + data[0]["options"]["styleClick"]["code"] + ')');
                        }else {
                            style = null;
                        }
                        if(data[0].hasOwnProperty("options")
                            && data[0]["options"] != null
                            && data[0]["options"].hasOwnProperty("click")
                            && data[0]["options"]["click"].hasOwnProperty("code")
                            && data[0]["options"]["click"]["code"] != ""){
                            callBack = eval('(' + data[0]["options"]["click"]["code"] + ')');
                        }else {
                            callBack = null;
                        }
                        if(style != null || callBack != null){
                            gis.addInteraction(data[i]["layerName"],"click",style,callBack);
                        }
                    }else if(!isForced){
                        gis.removeAllSelectInteraction();
                    }
                }
                gis.setZIndexById(data[i]["layerId"],len - 1 -i);
            }
        }
    }
</script>
</body>
</html>
